package com.exsun.ex1077.ui.activity.bounds

import android.Manifest
import android.content.Intent
import android.os.Bundle
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.*
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.PermissionUtils
import com.drake.brv.utils.*
import com.exsun.ex1077.BuildConfig
import com.exsun.ex1077.R
import com.exsun.ex1077.app.Constant
import com.exsun.ex1077.databinding.ActivityBoundsDrawBinding
import com.exsun.ex1077.model.BoundsStepCache
import com.exsun.ex1077.network.entity.Bounds
import com.exsun.ex1077.ui.popup.BoundsSavePopup
import com.lxj.xpopup.XPopup
import com.zhangping.amap.AMapHelper
import com.zhangping.amap.LocationHelper
import com.zhangping.amap.extend.getLatLng
import com.zhangping.amap.extend.isSuccess
import com.zhangping.fastjetpack.base.BaseActivity
import com.zhangping.fastjetpack.binding.visible
import com.zhangping.fastjetpack.extend.*
import com.zhangping.fastjetpack.extend.base.parseState
import com.zhangping.fastjetpack.extend.view.toView
import com.zhangping.fastjetpack.model.KeyValue
import com.zhangping.fastjetpack.model.Permission
import com.zhangping.fastjetpack.ui.popup.RequestPermissionPopup
import com.zhangping.fastjetpack.ui.popup.TreeSingleSelectPopup
import kotlinx.android.synthetic.main.activity_bounds_draw.*
import kotlinx.android.synthetic.main.map_bounds_point.view.*


/**
 * 描述：电子围栏绘制页面
 * 作者：ZhangPing
 * 创建时间：2023/3/27 10:43
 */
class BoundsDrawActivity: BaseActivity<BoundsDrawViewModel, ActivityBoundsDrawBinding>() {

    override fun title() = "绘制电子围栏"

    private lateinit var mapHelper: AMapHelper
    private lateinit var map: AMap
    private var isFirstLocation = true
    //线集合
    private val lineList = arrayListOf<Polyline>()
    //虚线
    private var dottedLine: Polyline? = null
    //拖拽图标
    private var dragIconMarker: Marker? = null
    //拖拽图标绑定的点
    private var dragBindingMarker: Marker? = null
    //步骤缓存
    private var stepCacheList = arrayListOf<BoundsStepCache>()
    //围栏保存弹窗
    private lateinit var boundsSavePopup: BoundsSavePopup
    //公司选择弹窗
    private lateinit var companySelectPopup: TreeSingleSelectPopup

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        mViewModel.pageType.set(intent.getIntExtra("pageType", Constant.PAGE_TYPE_BOUNDS_ADD))
        super.initView(savedInstanceState)
        initCommonView()
        requestPermission()
        initManualDraw()
        initSiteDraw()
        mViewModel.apply {
            loadDeptTree()
            if (!isAddMode()) previewDrawBounds(model.get())
        }
    }

    /**
     * 初始化地图控件
     */
    private fun initCommonView(){
        if (!isAddMode()){
            mViewModel.apply {
                model.set(intent.getSerializableExtra("model") as Bounds)
                title.set(model.get()?.name)
            }
        }
        map = mapView.map
        mapHelper = AMapHelper(map).apply {
            bindLifecycle(lifecycle, mapView)
            hideLogo()
            applyStyle()
            changeMapType(AMap.MAP_TYPE_SATELLITE)
            if (isAddMode()) moveMap(level = 18F)
        }
        map.setOnMapClickListener {
            if (isPreviewMode() || mViewModel.isSiteDraw.get()) return@setOnMapClickListener
            addManualPoint(it)
        }
        map.addOnMarkerDragListener(object : AMap.OnMarkerDragListener{
            override fun onMarkerDragStart(marker: Marker) {
                addStepCache()
                if (dragIconMarker == null){
                    updateDragIconMarker(marker)
                }
            }

            override fun onMarkerDrag(marker: Marker) {
                onPointDrag(marker)
            }

            override fun onMarkerDragEnd(marker: Marker) {

            }
        })
        map.setOnMarkerClickListener {
            updateDragIconMarker(it)
            return@setOnMarkerClickListener true
        }
        manualDraw.setOnClickListener {
            showConfirm("确定要切换到手动绘制吗？"){
                clearMap()
                stepCacheList.clear()
                siteListView.models = emptyList()
                mapHelper.addMyLocationMarker()
                mViewModel.isSiteDraw.set(false)
            }
        }
        siteDraw.setOnClickListener {
            showConfirm("确定要切换到现场绘制吗？"){
                clearMap()
                stepCacheList.clear()
                siteListView.models = emptyList()
                mapHelper.addMyLocationMarker(R.drawable.bounds_site_map_location, 40, 43, false)
                mapHelper.myLocationMarker?.let {
                    it.setAnchor(0.5F, 1.0F)
                    it.title = "点击下方“+”号按钮"
                    it.snippet = " 添加第1个采集点 "
                    it.showInfoWindow()
                }
                mViewModel.isSiteDraw.set(true)
            }
        }
        zoomUp.setOnClickListener {
            mapHelper.map.animateCamera(CameraUpdateFactory.zoomIn())
        }
        zoomDown.setOnClickListener {
            mapHelper.map.animateCamera(CameraUpdateFactory.zoomOut())
        }
        myLocation.setOnClickListener {
            mapHelper.moveToMyLocation()
        }
        companySelectPopup = XPopup.Builder(this)
            .popupHeight((screenHeight() * 0.5).toInt())
            .autoOpenSoftInput(false)
            .autoFocusEditText(false)
            .asCustom(TreeSingleSelectPopup(this){ item ->
                boundsSavePopup.setCompanyData(KeyValue(item.id, item.text))
            }) as TreeSingleSelectPopup
        boundsSavePopup = XPopup.Builder(this)
            .autoFocusEditText(false)
            .asCustom(BoundsSavePopup(this, "", {
                KeyboardUtils.hideSoftInput(this)
                companySelectPopup.show()
            }){ popupView, content, company ->
                mViewModel.apply {
                    if (pageType.get() == Constant.PAGE_TYPE_BOUNDS_ADD){
                        boundsAdd(content, company.key, pointList.map { it.position })
                    }else if (pageType.get() == Constant.PAGE_TYPE_BOUNDS_UPDATE){
                        boundsUpdate(content, company.key, pointList.map { it.position })
                    }
                }
            }) as BoundsSavePopup
        
        /** 现场打点开发调试用 **/
        if (BuildConfig.DEBUG){
            debugMode.visible()
            left.setOnClickListener {
                mapHelper.myLocationMarker?.apply {
                    position = LatLng(position.latitude, position.longitude - 0.0001)
                }
            }
            right.setOnClickListener {
                mapHelper.myLocationMarker?.apply {
                    position = LatLng(position.latitude, position.longitude + 0.0001)
                }
            }
            up.setOnClickListener {
                mapHelper.myLocationMarker?.apply {
                    position = LatLng(position.latitude + 0.0001, position.longitude)
                }
            }
            down.setOnClickListener {
                mapHelper.myLocationMarker?.apply {
                    position = LatLng(position.latitude - 0.0001, position.longitude)
                }
            }
        }
    }

    /**
     * 初始化手动绘制控件
     */
    private fun initManualDraw(){
        val pointList = mViewModel.pointList
        last.setOnClickListener {
            if (pointList.isEmpty()) return@setOnClickListener
            if (dragIconMarker == null){
                updateDragIconMarker(pointList.last())
            }else{
                val position = pointList.indexOf(dragBindingMarker)
                val newPosition = if (position == 0) pointList.lastIndex else position - 1
                updateDragIconMarker(pointList[newPosition])
            }
        }
        next.setOnClickListener {
            if (pointList.isEmpty()) return@setOnClickListener
            if (dragIconMarker == null){
                updateDragIconMarker(pointList.first())
            }else{
                val position = pointList.indexOf(dragBindingMarker)
                val newPosition = if (position == pointList.lastIndex) 0 else position + 1
                updateDragIconMarker(pointList[newPosition])
            }
        }
        delete.setOnClickListener {
            deletePoint()
        }
        cancel.setOnClickListener {
            if (stepCacheList.isNullOrEmpty()) return@setOnClickListener
            val stepCache = stepCacheList.removeLast()
            stepCacheRecovery(stepCache.pointLatLngList, stepCache.dragBindingPosition)
        }
        confirm.setOnClickListener {
            boundsSavePopup.show()
        }
        deleteBounds.setOnClickListener {
            showConfirm("确定要删除”${mViewModel.model.get()!!.name}“吗？"){
                mViewModel.boundsDelete().observe(this){
                    "删除成功".showToast()
                    setResult(RESULT_OK, Intent().putExtra("needDeleteId", mViewModel.model.get()!!.id))
                    finish()
                }
            }
        }
        updateBounds.setOnClickListener {
            mViewModel.apply {
                pageType.set(Constant.PAGE_TYPE_BOUNDS_UPDATE)
                //回显围栏
                model.get()?.mapxy?.aoLatLng?.let {
                    stepCacheRecovery(it.map { LatLng(it.lat, it.lng) })
                }
            }
        }
    }

    /**
     * 初始化现场绘制控件
     */
    private fun initSiteDraw(){
        siteListView.linear().divider {
            setDivider(1, true)
        }.setup {
            addType<Marker> { R.layout.item_bounds_site }
            onClick(R.id.delete){
                when(it){
                    R.id.delete -> {
                        showConfirm("确定要删除吗？"){
                            mViewModel.apply {
                                pointList[modelPosition].remove()
                                pointList.removeAt(modelPosition)
                                //重绘地图
                                stepCacheRecovery(pointList.map { it.position })
                                //刷新列表
                                siteListView.models = pointList
                            }
                        }
                    }
                }
            }
        }.models = emptyList()
        siteAdd.setOnClickListener {
            addSitePoint(mapHelper.myLocationMarker)
        }
        siteSubmit.setOnClickListener {
            boundsSavePopup.show()
        }
    }

    /**
     * 清空地图覆盖物
     */
    private fun clearMap(){
        map.clear()
        mViewModel.pointList.clear()
        lineList.clear()
        dottedLine = null
        dragIconMarker = null
        dragBindingMarker = null
        updateBottomPanelStatus()
        updateDistanceAndArea()
    }

    /**
     * 预览模式，回显围栏
     */
    private fun previewDrawBounds(model: Bounds?){
        //预览模式，回显围栏
        model?.let {
            it.mapxy?.aoLatLng?.let {
                val newLatLngList = it.map { LatLng(it.lat, it.lng) }
                stepCacheRecovery(newLatLngList)
                val bounds = LatLngBounds.builder().apply { newLatLngList.forEach { include(it) } }.build()
                mapHelper.moveMap(bounds, 200)
            }
            boundsSavePopup.setBoundsName(it.name)
            boundsSavePopup.setCompanyData(KeyValue(it.companyId, it.companyName))
            companySelectPopup.setInitCheckedId(it.companyId)
        }
    }

    override fun onBackPressed() {
        showConfirm("退出将不会保存任何数据，是否确定退出？"){
            super.onBackPressed()
        }
    }

    /**
     * 是添加模式
     */
    private fun isAddMode() = mViewModel.pageType.get() == Constant.PAGE_TYPE_BOUNDS_ADD

    /**
     * 是编辑模式
     */
    private fun isUpdateMode() = mViewModel.pageType.get() == Constant.PAGE_TYPE_BOUNDS_UPDATE

    /**
     * 是编辑模式
     */
    private fun isPreviewMode() = mViewModel.pageType.get() == Constant.PAGE_TYPE_BOUNDS_PREVIEW

    /**
     * 步骤缓存恢复
     */
    private fun stepCacheRecovery(pointLatLngList: List<LatLng>, dragBindingPosition: Int = -1){
        val pointList = mViewModel.pointList
        val srcPointList = ArrayList(pointList)
        //清空地图
        clearMap()
        if (mViewModel.isSiteDraw.get()){
            /** 现场绘制 **/
            //添加我的位置
            mapHelper.addMyLocationMarker(R.drawable.bounds_site_map_location, 40, 43, false)
            if (pointLatLngList.isNullOrEmpty()){
                mapHelper.myLocationMarker?.let {
                    it.setAnchor(0.5F, 1.0F)
                    it.title = "点击下方“+”号按钮"
                    it.snippet = " 添加第1个采集点 "
                    it.showInfoWindow()
                }
            }
            //回显围栏
            pointLatLngList.forEachIndexed { index, latLng ->
                //新增点
                val view = R.layout.map_bounds_point.toView()
                val marker = map.addMarker(MarkerOptions()
                    .position(latLng)
                    .anchor(0.5F, 0.5F)
                    .title("途经点${index + 1}")
                    .snippet(srcPointList[index].snippet)
                    .icon(BitmapDescriptorFactory.fromView(view.apply {
                        this.index.text = (pointList.size + 1).toString()
                    })))
                //点与点之间进行连线
                if (pointList.isNotEmpty()){
                    val line = map.addPolyline(PolylineOptions()
                        .add(pointList.last().position)
                        .add(marker.position)
                        .width(dp2px(3).toFloat())
                        .color(R.color.color_C6E8A5.toColorRes()))
                    lineList.add(line)
                }
                pointList.add(marker)
                //新增点与首个点进行虚线链接
                if (pointList.size > 2){
                    dottedLine?.let {
                        it.remove()
                        lineList.remove(it)
                    }
                    dottedLine = map.addPolyline(PolylineOptions()
                        .add(pointList.last().position)
                        .add(pointList.first().position)
                        .width(dp2px(3).toFloat())
                        .setDottedLine(true)
                        .color(R.color.color_C6E8A5.toColorRes()))
                    lineList.add(dottedLine!!)
                }
            }
        }else{
            /** 手动绘制 **/
            //添加我的位置
            mapHelper.addMyLocationMarker()
            //回显围栏
            pointLatLngList.forEachIndexed { index, latLng ->
                val srcIcon = if (index == pointLatLngList.lastIndex) R.drawable.map_point_blue else R.drawable.map_point_green
                val marker = map.addMarker(MarkerOptions()
                    .position(latLng)
                    .anchor(0.5F, 0.5F)
                    .draggable(true)
                    .icon(BitmapDescriptorFactory.fromBitmap(srcIcon.toBitmap(40, 40))))
                if (mViewModel.pageType.get() == Constant.PAGE_TYPE_BOUNDS_PREVIEW) {
                    //预览模式不可拖拽，不可点击
                    marker.isDraggable = false
                    marker.isClickable = false
                }
                mViewModel.pointList.add(marker)
                //点与点之间进行连线
                if (index > 0){
                    //与上一个点进行实线连接
                    val line1 = map.addPolyline(PolylineOptions()
                        .add(pointLatLngList[index - 1])
                        .add(latLng)
                        .width(dp2px(3).toFloat())
                        .color(R.color.color_C6E8A5.toColorRes()))
                    lineList.add(line1)
                    //如果是最后一个点，则与第一个点连接，预览模式使用实线，添加和编辑模式使用虚线
                    if (index == pointLatLngList.lastIndex && pointLatLngList.size > 2){
                        dottedLine = map.addPolyline(PolylineOptions()
                            .add(latLng)
                            .add(pointLatLngList.first())
                            .width(dp2px(3).toFloat())
                            .setDottedLine(mViewModel.pageType.get() != Constant.PAGE_TYPE_BOUNDS_PREVIEW)
                            .color(R.color.color_C6E8A5.toColorRes()))
                        lineList.add(dottedLine!!)
                    }
                }
            }
            //添加拖拽图标
            if (dragBindingPosition >= 0){
                updateDragIconMarker(mViewModel.pointList[dragBindingPosition])
            }
        }
        //更新底部面板状态
        updateDistanceAndArea()
        updateBottomPanelStatus()
    }

    /**
     * 添加步骤缓存
     * 开始新的操作时，先缓存当前的状态
     */
    private fun addStepCache(){
        stepCacheList.add(BoundsStepCache(mViewModel.pointList.map { it.position },
            if (dragBindingMarker == null) -1 else mViewModel.pointList.indexOf(dragBindingMarker)))
    }

    /**
     * 删除点
     */
    private fun deletePoint(){
        val pointList = mViewModel.pointList
        if (pointList.isEmpty()) return
        addStepCache()
        val position = if (dragBindingMarker == null) pointList.size - 1 else pointList.indexOf(dragBindingMarker)
        //删除当前点和前一根线
        if (lineList.isNotEmpty()){
            lineList.apply {
                val newPosition = Math.max(0, position - 1)
                get(newPosition).remove()
                removeAt(newPosition)
            }
        }
        pointList.apply {
            pointList[position].remove()
            pointList.removeAt(position)
            if (this.isNotEmpty()){
                //更新选中点为被删除点的前一个
                updateDragIconMarker(pointList[Math.max(0, position - 1)])
            }
        }
        when {
            pointList.size >= 3 -> {
                //将虚线重新连接
                if (position == 0){
                    //是第一个点被删除
                    lineList.last().points = arrayListOf(
                        pointList.last().position,
                        pointList.first().position
                    )
                }else{
                    //非第一个点被删除
                    lineList[position - 1].points = arrayListOf(
                        pointList[position - 1].position, //被删除点的前一个点
                        pointList[if (position > pointList.lastIndex) 0 else position].position //被删除点的后一个点或第一个点
                    )
                }
            }
            pointList.size > 0 -> {
                //删除虚线
                if (lineList.isNotEmpty()){
                    lineList.last().remove()
                    lineList.removeLast()
                }
                //将最后一根线重新连接
                if (pointList.size == 2 && lineList.size == 1){
                    lineList[0].points = arrayListOf(pointList.first().position, pointList.last().position)
                }
            }
            else -> {
                //重置拖拽图标
                dragIconMarker?.remove()
                dragIconMarker = null
                dragBindingMarker = null
            }
        }
        updateDistanceAndArea()
        updateBottomPanelStatus()
    }

    /**
     * 添加手动绘制点
     */
    private fun addManualPoint(latLng: LatLng){
        addStepCache()
        val pointList = mViewModel.pointList
        //将所有已存在的点更新为绿色
        pointList.forEach {
            it.setIcon(BitmapDescriptorFactory.fromBitmap(R.drawable.map_point_green.toBitmap(40, 40)))
        }
        //新增点为蓝色
        val marker = map.addMarker(MarkerOptions()
            .position(latLng)
            .anchor(0.5F, 0.5F)
            .draggable(true)
            .icon(BitmapDescriptorFactory.fromBitmap(R.drawable.map_point_blue.toBitmap(40, 40))))
        //点与点之间进行连线
        if (pointList.isNotEmpty()){
            val line = map.addPolyline(PolylineOptions()
                .add(pointList.last().position)
                .add(marker.position)
                .width(dp2px(3).toFloat())
                .color(R.color.color_C6E8A5.toColorRes()))
            lineList.add(line)
        }
        //新增点添加到点集合
        pointList.add(marker)
        //新增点与首个点进行虚线链接
        if (pointList.size > 2){
            dottedLine?.let {
                it.remove()
                lineList.remove(it)
            }
            dottedLine = map.addPolyline(PolylineOptions()
                .add(pointList.last().position)
                .add(pointList.first().position)
                .width(dp2px(3).toFloat())
                .setDottedLine(true)
                .color(R.color.color_C6E8A5.toColorRes()))
            lineList.add(dottedLine!!)
            //添加拖拽图标
            updateDragIconMarker(marker)
        }
        updateBottomPanelStatus()
        updateDistanceAndArea()
    }

    /**
     * 添加实地绘制点
     */
    private fun addSitePoint(locationMarker: Marker?){
        if (locationMarker == null) return
        mapHelper.myLocationMarker?.hideInfoWindow()
        val pointList = mViewModel.pointList
        //更新所有已存在的点序号
        pointList.forEachIndexed { index, marker ->
            val view = R.layout.map_bounds_point.toView()
            marker.setIcon(BitmapDescriptorFactory.fromView(view.apply {
                this.index.text = (index + 1).toString()
            }))
        }
        //新增点
        val view = R.layout.map_bounds_point.toView()
        val marker = map.addMarker(MarkerOptions()
            .position(locationMarker.position)
            .anchor(0.5F, 0.5F)
            .title("途经点${pointList.size + 1}")
            .snippet(locationMarker.`object`?.let { it as String } ?: "未知地址")
            .icon(BitmapDescriptorFactory.fromView(view.apply {
                index.text = (pointList.size + 1).toString()
            })))
        //点与点之间进行连线
        if (pointList.isNotEmpty()){
            val line = map.addPolyline(PolylineOptions()
                .add(pointList.last().position)
                .add(marker.position)
                .width(dp2px(3).toFloat())
                .color(R.color.color_C6E8A5.toColorRes()))
            lineList.add(line)
        }
        pointList.add(marker)
        //新增点与首个点进行虚线链接
        if (pointList.size > 2){
            dottedLine?.let {
                it.remove()
                lineList.remove(it)
            }
            dottedLine = map.addPolyline(PolylineOptions()
                .add(pointList.last().position)
                .add(pointList.first().position)
                .width(dp2px(3).toFloat())
                .setDottedLine(true)
                .color(R.color.color_C6E8A5.toColorRes()))
            lineList.add(dottedLine!!)
        }
        //更新途径点列表
        siteListView.models = pointList
        updateBottomPanelStatus()
        updateDistanceAndArea()
    }

    /**
     * 更新底部面板状态
     */
    private fun updateBottomPanelStatus(){
        val pointList = mViewModel.pointList
        if (pointList.isEmpty()){
            last.alpha = 0.6F
            last.isClickable = false
            delete.alpha = 0.6F
            delete.isClickable = false
            cancel.alpha = 0.6F
            cancel.isClickable = false
            next.alpha = 0.6F
            next.isClickable = false
        }else {
            last.alpha = 1.0F
            last.isClickable = true
            delete.alpha = 1.0F
            delete.isClickable = true
            cancel.alpha = 1.0F
            cancel.isClickable = true
            next.alpha = 1.0F
            next.isClickable = true
        }
    }

    /**
     * 更新拖拽图标位置
     */
    private fun updateDragIconMarker(byBindingMarker: Marker){
        if (dragIconMarker == null){
            dragIconMarker = map.addMarker(MarkerOptions()
                .position(byBindingMarker.position)
                .draggable(true)
                .icon(BitmapDescriptorFactory.fromBitmap(R.drawable.map_point_drag.toBitmap(40, 58))))
        }else{
            dragIconMarker?.position = byBindingMarker.position
        }
        dragIconMarker?.setToTop()
        dragBindingMarker = byBindingMarker
    }

    /**
     * 当点拖拽时
     */
    private fun onPointDrag(marker: Marker){
        val pointList = mViewModel.pointList
        val position = if (marker == dragIconMarker) {
            //拖拽的是拖拽图标，设置绑定的点一起更新位置
            dragBindingMarker!!.position = marker.position
            pointList.indexOf(dragBindingMarker)
        } else {
            //拖拽的是点，设置拖拽图标一起更新位置
            dragIconMarker?.apply {
                position = marker.position
                setToTop()
            }
            pointList.indexOf(marker)
        }
        if (position == 0) {
            //被拖拽的点是第一个点，则此点的连接线是第一条和最后一条线(虚线)
            lineList.first().points = arrayListOf(marker.position, pointList[1].position)
            lineList.last().points = arrayListOf(pointList.last().position, marker.position)
        }else if (position == pointList.lastIndex){
            //被拖拽的点是最后一个点，则此点的连接线是最后两条线
            lineList.last().points = arrayListOf(marker.position, pointList[0].position)
            lineList[lineList.lastIndex - 1].points = arrayListOf(pointList[pointList.lastIndex - 1].position, marker.position)
        }else{
            //被拖拽的点是中间点
            lineList[position].points = arrayListOf(marker.position, pointList[position + 1].position)
            lineList[position - 1].points = arrayListOf(pointList[position - 1].position, marker.position)
        }
        updateDistanceAndArea()
    }

    /**
     * 更新周长和面积
     */
    private fun updateDistanceAndArea(){
        //更新周长
        var totalDistance = 0F
        lineList.forEach {
            totalDistance += AMapUtils.calculateLineDistance(it.points.first(), it.points.last())
        }
        distance.text = "周长：${totalDistance.round45(2)}m"
        //更新面积
        area.text = "面积：${AMapUtils.calculateArea(mViewModel.pointList.map { it.position }).round45(2)}㎡"
    }

    /**
     * 申请定位权限
     */
    private fun requestPermission(){
        RequestPermissionPopup.create(this, arrayListOf(
            Permission("地理位置", "使用电子围栏绘制功能，需要获取您的位置信息", arrayListOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ))
        )) { isAllGranted, granted, deniedForever, denied ->
            if (!isAllGranted) {
                "定位权限授权被拒绝，将无法使用现场绘制功能！".showLongToast()
                return@create
            }
            LocationHelper.startLocation()
        }.show()
    }

    override fun createObserver() {
        super.createObserver()
        LocationHelper.locationLiveData.observe(this){
            if (!it.isSuccess()) return@observe
            if (isFirstLocation){
                isFirstLocation = false
                mapHelper.addMyLocationMarker()
                mapHelper.myLocationMarker?.`object` = it.address
                if (isAddMode()) mapHelper.moveMap(it.getLatLng())
            }else{
                mapHelper.myLocationMarker?.apply {
                    position = it.getLatLng()
                    `object` = it.address
                    if (!mViewModel.isSiteDraw.get()) rotateAngle = it.bearing
                }
            }
            address.text = it.address
        }
        mViewModel.apply {
            deptTreeResult.observe(this@BoundsDrawActivity){
                parseState(it, {
                    companySelectPopup.setNewData(it)
                })
            }
            boundsAddResult.observe(this@BoundsDrawActivity){
                parseState(it, {
                    "添加成功".showToast()
                    setResult(RESULT_OK, Intent().putExtra("needRefresh", true))
                    finish()
                })
            }
            boundsUpdateResult.observe(this@BoundsDrawActivity){
                parseState(it, {
                    "围栏数据更新成功".showToast()
                    setResult(RESULT_OK, Intent().putExtra("needUpdateId", model.get()!!.id))
                    finish()
                })
            }
        }
    }

    override fun onDestroy() {
        //恢复定位间隔为60秒
        LocationHelper.startLocation(60 * 1000)
        super.onDestroy()
    }

}